﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace cjwygl
{
    public partial class FrmGenerate : Form
    {
        private DateTime mMonthBegin;
        private DateTime mMonthEnd;
        private String mMonth = "";

        private int mTotalCount = -1;
        private int mCurrentCount = 0;
        private bool mCompleted = false;
        private bool mSucceed = false;
        private String mMessage = "";

        public FrmGenerate()
        {
            InitializeComponent();
        }

        private void button_generate_Click(object sender, EventArgs e)
        {
            mMonthBegin = dateTimePicker1.Value;
            mMonthEnd = dateTimePicker1.Value.AddMonths(1).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
            mMonth = dateTimePicker1.Value.ToString("yyyyMM");

            mTotalCount = -1;
            mCurrentCount = 0;
            mCompleted = false;
            mSucceed = false;
            mMessage = "";

            label2.Visible = true;
            button_generate.Enabled = false;
            dateTimePicker1.Enabled = false;

            Thread t = new Thread(new ThreadStart(generate));
            t.Start();

            timer1.Enabled = true;


        }


        private void generate()
        {
            if (CheckIfExist())
            {
                mMessage = "所选月份已经生成过报表。";
                mCompleted = true;
                return;
            }

            // 获取车位费单价
            double dParkingFee = 150;
            using (DataBase db = new DataBase())
            {
                DataTable dtFeeBase = db.ExecuteDataTable("SELECT * FROM CJ_FEE_BASE WHERE UNIT_NAME='车位'");
                if (dtFeeBase.Rows.Count > 0)
                {
                    String sParkingUnitPrice = dtFeeBase.Rows[0]["UNIT_PRICE"].ToString();
                    double.TryParse(sParkingUnitPrice, out dParkingFee);
                }
            }

            // 获取所有未终止客户列表
            DataTable dtCustomers;
            using (DataBase db = new DataBase())
            {
                dtCustomers = db.ExecuteDataTable("SELECT * FROM CJ_CUSTOMER_INFO WHERE CONTRACT_TERMINATE=0");
            }

            // 遍历所有客户
            mTotalCount = dtCustomers.Rows.Count;
            for (mCurrentCount = 0; mCurrentCount < mTotalCount; mCurrentCount++)
            {
                DataRow drCustom = dtCustomers.Rows[mCurrentCount];

                if (((DateTime)drCustom["CONTRACT_END_DATE"]) < mMonthBegin)
                {
                    // 合同已结束的客户不处理
                    continue;
                }

                String COMPANY_ID = drCustom["ID"].ToString();
                int iCompanyID = -1;
                int.TryParse(COMPANY_ID, out iCompanyID);

                DateTime? lastNextStartTime = getLastNextStartTime(COMPANY_ID);

                DateTime lastEnd;
                DateTime nextStart;

                if (lastNextStartTime == null)
                {
                    // 新客户
                    DateTime dtContractStart = (DateTime)drCustom["CONTRACT_START_DATE"];
                    dtContractStart = dtContractStart.AddMonths(3);
                    if (dtContractStart > mMonthEnd)
                    {
                        continue;
                    }

                    lastEnd = dtContractStart;
                }
                else
                {
                    if (lastNextStartTime.Value > mMonthEnd)
                    {
                        continue;
                    }

                    lastEnd = lastNextStartTime.Value;
                }

                nextStart = lastEnd.AddMonths(3);


                double dMonthlyRental = 0;
                double.TryParse(drCustom["MONTHLY_RENTAL"].ToString(), out dMonthlyRental);

                double dParkingCount = 0;
                double.TryParse(drCustom["PARKING_COUNT"].ToString(), out dParkingCount);


                if (dMonthlyRental != 0)
                {
                    //TODO: 合同终止日记介于lastEnd和nextStart之间
                    addMainFee("房租", dMonthlyRental * 3, lastEnd, nextStart, "", iCompanyID);
                    // 服务费==房租？
                    addMainFee("服务费", dMonthlyRental * 3, lastEnd, nextStart, "", iCompanyID);
                }
                

                if (dParkingCount != 0)
                {
                    addMainFee("车位", dParkingFee * dParkingCount, lastEnd, nextStart, "", iCompanyID);
                }

                // 获取MISC_FEE表中最新没有交的水费
                using (DataBase db = new DataBase())
                {
                    db.AddParameter("COMPANY_ID", COMPANY_ID);
                    DataTable dtMiscFee = db.ExecuteDataTable("SELECT TOP 1 * FROM CJ_MISC_FEE WHERE FEE_TYPE='水费' AND COMPANY_ID=@COMPANY_ID AND IS_PAID=0 ORDER BY CB_TIME DESC");
                    if (dtMiscFee.Rows.Count > 0)
                    {
                        DateTime dtCBTime;
                        DateTime.TryParse(dtMiscFee.Rows[0]["CB_TIME"].ToString(), out dtCBTime);

                        double dFee = 0;
                        double.TryParse(dtMiscFee.Rows[0]["CB_FEE"].ToString(), out dFee);

                        if (dFee != 0)
                            addMainFee("水费", dFee, dtCBTime, null, dtMiscFee.Rows[0]["CB_COMMENT"].ToString(), iCompanyID);
                    }
                }

                // 获取MISC_FEE表中最新没有交的电费
                using (DataBase db = new DataBase())
                {
                    db.AddParameter("COMPANY_ID", COMPANY_ID);
                    DataTable dtMiscFee = db.ExecuteDataTable("SELECT TOP 1 * FROM CJ_MISC_FEE WHERE FEE_TYPE='电费' AND COMPANY_ID=@COMPANY_ID AND IS_PAID=0 ORDER BY CB_TIME DESC");
                    if (dtMiscFee.Rows.Count > 0)
                    {
                        DateTime dtCBTime;
                        DateTime.TryParse(dtMiscFee.Rows[0]["CB_TIME"].ToString(), out dtCBTime);

                        double dFee = 0;
                        double.TryParse(dtMiscFee.Rows[0]["CB_FEE"].ToString(), out dFee);

                        if (dFee != 0)
                            addMainFee("电费", dFee, dtCBTime, null, dtMiscFee.Rows[0]["CB_COMMENT"].ToString(), iCompanyID);
                    }
                }
                

                //addMainFee("物业", 0, lastEnd, nextStart, "", iCompanyID);
                //addMainFee("网络", 0, lastEnd, nextStart, "", iCompanyID);
                //addMainFee("复印", 0, lastEnd, nextStart, "", iCompanyID);
            }

            


            mSucceed = true;
            mMessage = "报表生成成功";
            mCompleted = true;
            
            
        }

        private int addMainFee(String FEE_TYPE, double FEE, DateTime LAST_END, DateTime? NEXT_START, String COMMENT, int COMPANY_ID)
        {
            String sql = "INSERT INTO [CJ_MAIN_FEE]([FEE_TYPE],[FEE],[LAST_END],[NEXT_START],[COMMENT],[OP_NAME]"+
                            ",[OP_ID],[LOG_TIME],[LAST_MODIFY_DATE],[MODIFY_COMMENT],[COMPANY_ID],[IS_PAID],[GEN_MONTH])"+
                            "VALUES (@FEE_TYPE,@FEE,@LAST_END,@NEXT_START,@COMMENT,@OP_NAME,@OP_ID,@LOG_TIME"+
                            ",@LAST_MODIFY_DATE,@MODIFY_COMMENT,@COMPANY_ID,0,@GEN_MONTH)";

            using (DataBase db = new DataBase())
            {
                db.AddParameter("FEE_TYPE", FEE_TYPE);
                db.AddParameter("FEE", FEE);
                db.AddParameter("LAST_END", LAST_END);
                if (NEXT_START == null)
                    db.AddParameter("NEXT_START", DBNull.Value);
                else
                    db.AddParameter("NEXT_START", NEXT_START);
                db.AddParameter("COMMENT", COMMENT);
                db.AddParameter("OP_NAME", userinfo.username);
                db.AddParameter("OP_ID", userinfo.id);
                db.AddParameter("LOG_TIME", DateTime.Now);
                db.AddParameter("LAST_MODIFY_DATE", DateTime.Now);
                db.AddParameter("MODIFY_COMMENT", DateTime.Now.ToString() + ":" + userinfo.username + "生成了该条记录;");
                db.AddParameter("COMPANY_ID", COMPANY_ID);
                db.AddParameter("GEN_MONTH", mMonth);

                return db.ExecuteNonQuery(sql);
            }


        }

        private DateTime? getLastNextStartTime(String company_id)
        {
            using (DataBase db = new DataBase())
            {
                db.AddParameter("COMPANY_ID", company_id);
                // 得到最大的NextTime。  
                // 
                DataTable dt = db.ExecuteDataTable("SELECT MAX([NEXT_START]) FROM [CJ_MAIN_FEE] WHERE [COMPANY_ID]=@COMPANY_ID");
                if (dt.Rows.Count == 1)
                {
                    if (dt.Rows[0][0].ToString() == "")
                        return null;
                    return (DateTime?)dt.Rows[0][0];
                }
            }
            return null;
        }

        private bool CheckIfExist()
        {
            using (DataBase db = new DataBase())
            {

                //DataTable dt = db.ExecuteDataTable("SELECT TOP 1 * FROM [CJ_MAIN_FEE] WHERE [LAST_END] >= '" + mMonthBegin.ToString() + "' AND [LAST_END] <= '" + mMonthEnd.ToString() + "'");
                DataTable dt = db.ExecuteDataTable("SELECT TOP 1 * FROM [CJ_MAIN_FEE] WHERE [GEN_MONTH] = '" + mMonth + "'");
                if (dt.Rows.Count > 0)
                    return true;
            }
            return false;
        }

        private void FrmGenerate_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Value = dateTimePicker1.Value.AddDays(1 - dateTimePicker1.Value.Day).Date;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (mCompleted)
            {
                timer1.Enabled = false;
                label2.Visible = false;
                button_generate.Enabled = true;
                dateTimePicker1.Enabled = true;


                if (mSucceed)
                {
                    MessageBox.Show(mMessage, "生成费用报表", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Dispose();
                }
                else
                {
                    MessageBox.Show(mMessage, "生成费用报表", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                try
                {
                    if (mTotalCount > 0)
                    {
                        if (progressBar1.Style != ProgressBarStyle.Blocks)
                            progressBar1.Style = ProgressBarStyle.Blocks;
                        if (progressBar1.Maximum != mTotalCount)
                            progressBar1.Maximum = mTotalCount;
                        progressBar1.Value = mCurrentCount;
                    }
                    else
                    {
                        if (progressBar1.Style != ProgressBarStyle.Marquee)
                            progressBar1.Style = ProgressBarStyle.Marquee;
                    }
                }
                catch
                {
                }
            }
        }

        private void FrmGenerate_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!button_generate.Enabled)
            {
                e.Cancel = true;
            }
        }



    }
}
